package com.newland.mesdk.demo.fragment;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.newland.mesdk.demo.main.R;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtype.module.common.keyboard.KeyBoardReadingEvent;
import com.newland.mtype.module.common.lcd.DispType;
import com.newland.mesdk.demo.interfaceimpl.KeyBoardInterfaceImpl;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF 密码键盘模块
 */
public class KeyBoardFragment extends Fragment implements OnClickListener {
	private MainActivity mainActivity;
	private int inputLen = 0;
	private TextView tvOperationMessage;
	private StringBuffer stringBuffer;
	private KeyBoardInterfaceImpl keyBoardInterfaceImpl;
	private Button btnGetKeyValue, btnGetNum, btnGetPass, btnGetStr, btnCancle;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_keyboard, null);
		mainActivity = (MainActivity) getActivity();
		tvOperationMessage = (TextView) mainActivity.findViewById(R.id.test_info);
		initKeyBoardView(view);
		return view;
	}

	public void initKeyBoardView(View view) {
		btnGetKeyValue = (Button) view.findViewById(R.id.btn_keyboard_get_keyboardvalue);
		btnGetKeyValue.setOnClickListener(this);

		btnGetNum = (Button) view.findViewById(R.id.btn_keyboard_get_number);
		btnGetNum.setOnClickListener(this);

		btnGetPass = (Button) view.findViewById(R.id.btn_keyboard_get_password);
		btnGetPass.setOnClickListener(this);

		btnGetStr = (Button) view.findViewById(R.id.btn_keyboard_get_string);
		btnGetStr.setOnClickListener(this);

		btnCancle = (Button) view.findViewById(R.id.btn_keyboard_cancle);
		btnCancle.setOnClickListener(this);
	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2: // 键盘输入
				int len = (Integer) msg.obj;
				stringBuffer = new StringBuffer();
				for (int i = 0; i < len; i++) {
					stringBuffer.append(" * ");
				}
				tvOperationMessage.setText("正在密码输入:" + stringBuffer.toString());
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void onClick(View v) {
		if (mainActivity.isDeviceInit()) {
			mainActivity.connectDevice();
			keyBoardInterfaceImpl = new KeyBoardInterfaceImpl();
			switch (v.getId()) {
			case R.id.btn_keyboard_get_keyboardvalue:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								int value;
								mainActivity.processingLock();
								mainActivity.showMessage("请按密码键盘：" + "\r\n", MessageTag.DATA);
								value = keyBoardInterfaceImpl.read(20, TimeUnit.SECONDS) & 0xff;
								mainActivity.showMessage("在限定时间内，读取按键值：" + value + "\r\n", MessageTag.DATA);
								mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("在限定时间内，读取按键值 异常！" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

				}

				break;
			case R.id.btn_keyboard_get_string:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								mainActivity.showMessage("请输入字符串，并以确认键结束", MessageTag.TIP);
								DeviceEventListener<KeyBoardReadingEvent<String>> listener = new DeviceEventListener<KeyBoardReadingEvent<String>>() {
									@Override
									public Handler getUIHandler() {
										return null;
									}

									@Override
									public void onEvent(KeyBoardReadingEvent<String> event, Handler arg1) {
										if (event instanceof KeyBoardReadingEvent && ((KeyBoardReadingEvent<String>) event).isProcessing()) {
											mainActivity.showMessage("正在输入字符串", MessageTag.TIP);
											return;
										}
										if (event instanceof KeyBoardReadingEvent && ((KeyBoardReadingEvent<String>) event).isSuccess()) {
											mainActivity.showMessage("按键输入为：" + event.getWholeKeyWord(), MessageTag.DATA);
											mainActivity.processingUnLock();
											return;
										}
										if (event.isUserCanceled()) {
											mainActivity.showMessage("用户取消字符串！" + "\r\n", MessageTag.NORMAL);
											mainActivity.processingUnLock();
										}else {
											mainActivity.showMessage("字符串输入错误" + "\r\n", MessageTag.NORMAL);
											mainActivity.processingUnLock();
										}
									}
								};

								keyBoardInterfaceImpl.readString(DispType.NORMAL, "字符串", "", 1, 12, 60, TimeUnit.SECONDS, listener);
								mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("开启一个标准字符串读取流程 异常！" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();
				}

				break;
			case R.id.btn_keyboard_get_number:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								mainActivity.showMessage("请输入数字，以“确定”键结束" + "\r\n", MessageTag.TIP);
								keyBoardInterfaceImpl.readNumber(DispType.NORMAL, "数字", "number", 1, 12, 20, TimeUnit.SECONDS,
										new DeviceEventListener<KeyBoardReadingEvent<BigDecimal>>() {
											@Override
											public void onEvent(KeyBoardReadingEvent<BigDecimal> event, Handler handler) {
												if (event instanceof KeyBoardReadingEvent
														&& ((KeyBoardReadingEvent<BigDecimal>) event).isProcessing()) {
													mainActivity.showMessage("正在输入数字", MessageTag.TIP);
													return;
												}
												if (event instanceof KeyBoardReadingEvent && ((KeyBoardReadingEvent<BigDecimal>) event).isSuccess()) {
													mainActivity.showMessage("按键输入数字为：" + event.getWholeKeyWord(), MessageTag.DATA);
													mainActivity.processingUnLock();
													return;
												}
												if (event.isUserCanceled()) {
													mainActivity.showMessage("用户取消数字输入！" + "\r\n", MessageTag.NORMAL);
													mainActivity.processingUnLock();
												}
											}

											@Override
											public Handler getUIHandler() {
												return null;
											}

										});

							} catch (Exception e) {
								mainActivity.showMessage("开启一个标准数字读取流程 异常！" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();
				}

				break;
			case R.id.btn_keyboard_get_password:
				if (mainActivity.processingisLocked()) {
					mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
				} else {
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								mainActivity.showMessage("请输入6位密码，以“确定”键结束" + "\r\n", MessageTag.TIP);
								keyBoardInterfaceImpl.readPwd(DispType.NORMAL, "密码", "pwd", 1, 12, 20, TimeUnit.SECONDS,
										new DeviceEventListener<KeyBoardReadingEvent<String>>() {
											@Override
											public void onEvent(KeyBoardReadingEvent<String> event, Handler handler) {
												if (event instanceof KeyBoardReadingEvent && ((KeyBoardReadingEvent<String>) event).isProcessing()) {
													inputLen = inputLen + 1;
													Message msg = mHandler.obtainMessage(2);
													msg.obj = inputLen;
													msg.sendToTarget();
													return;
												}
												if (event instanceof KeyBoardReadingEvent && ((KeyBoardReadingEvent<String>) event).isSuccess()) {
													inputLen=0;
													mainActivity.showMessage("按键输入密码为：" + event.getWholeKeyWord(), MessageTag.DATA);
													mainActivity.processingUnLock();
													return;
												}
												if (event.isUserCanceled()) {
													inputLen=0;
													mainActivity.showMessage("用户取消密码输入！" + "\r\n", MessageTag.NORMAL);
													mainActivity.processingUnLock();
												} else {
													inputLen=0;
													mainActivity.showMessage("密码输入错误！密码长度是否为6位！" + "\r\n", MessageTag.ERROR);
													mainActivity.processingUnLock();
												}
											}

											@Override
											public Handler getUIHandler() {
												return null;
											}

										});

							} catch (Exception e) {
								mainActivity.showMessage("开启一个标准字密码读取流程 异常！" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();
				}

				break;
			case R.id.btn_keyboard_cancle:
				new Thread(new Runnable() {

					@Override
					public void run() {
						try {
							mainActivity.processingLock();
							keyBoardInterfaceImpl.cancelLastReading();
							mainActivity.showMessage("撤消上次读取操作 成功" + "\r\n", MessageTag.NORMAL);
							mainActivity.processingUnLock();

						} catch (Exception e) {
							mainActivity.showMessage("撤消上次读取操作 异常" + e + "\r\n", MessageTag.ERROR);
							mainActivity.processingUnLock();
						}

					}
				}).start();

				break;

			default:
				break;
			}
		} else {
			mainActivity.showMessage("设备未初始化，请先初始化！" + "\r\n", MessageTag.NORMAL);
		}
	}

}
